#!/usr/bin/env python
# -*- coding: utf-8 *-*

#   This file is part of Sql-Rice.
#
#    Sql-Rice is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    Sql-Rice is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Sql-Rice; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
import sys
sys.path.append('/archivos/source/sql_rice')

import cmd
from rules import models
from utils.common_lambda import do_nothing


class RuleEditor(cmd.Cmd):

    prompt = 'rule:>>'
    intro = ''

    def _add_rule(self, name, val, field):
        if field is None:
            field = models.Rule(pattern=name)
        validator = models.Validator.get_by(name=val)
        field.validators.append(validator)
        models.session.commit()

    def _rem_rule(self, name, val, field):
        if field is None:
            self.stdout.write('no field named %s' % name)
        else:
            validator = models.Validator.get_by(name=val)
            try:
                field.validators.remove(validator)
                models.session.commit()
            except ValueError:
                self.stdout.write('rule %s not aplied to %s' % (val, name))

    def _list_rules(self, name, val, field):
        if field is None:
            self.stdout.write('field %s not registred' % name)
        else:
            for v in field.validators:
                self.stdout.write(v.name)

    def do_field(self, args):
        '''apply/remove validator to a specific field
        usage: field <name> [add|rem|list] [validator name]
        example: field rut add rut'''
        args = unicode(args)
        try:
            name, action, val = args.split()
        except ValueError:
            name, action = args.split()
            val = None
        field = models.Rule.get_by(pattern=name)
        switch = {'add': self._add_rule,
                  'rem': self._rem_rule,
                  'list': self._list_rules}
        switch.get(action, do_nothing)(name, val, field)

    def do_list(self, arg):
        self.stdout.write(_builtins)

    def do_quit(self, args):
        raise KeyboardInterrupt()

    def emptyline(self):
        pass


_builtins = [u'rut', u'date', u'natural', u'maximum']


def main(filename=''):
    if filename:
        models.metadata.bind = u'sqlite:///%s' % filename
    else:
        models.metadata.bind = u'sqlite:///:memory:'
        print 'RULEDIT IS WORKING IN MEMORY MODE'

    models.setup_all(True)
    for v in _builtins:
        models.Validator(name=v)
    models.session.commit()
    interpreter = RuleEditor()
    try:
        interpreter.cmdloop()
    except KeyboardInterrupt:
        print 'bye'

if __name__ == '__main__':
    import plac
    plac.call(main)
